package com.hiwan.unions.application.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.hiwan.unions.adapter.bean.MembersAdresssBean;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.exception.ApiException;
import com.hiwan.unions.application.interfac.IService;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.Utils;
import com.yanzhenjie.nohttp.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by llg on 2017/2/17.
 */
public class LocalService extends Service {
    protected SharedPreferences userInfoC;
    protected LocationService locationService;
    private ArrayList<MembersAdresssBean> arry_address = new ArrayList<MembersAdresssBean>();
    MembersAdresssBean bean;
    private String city = "成都市";
    boolean types = false;
    private Intent intent = new Intent("com.example.communication.RECEIVER");

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        userInfoC = getSharedPreferences(ConstantsValues.APP,
                Context.MODE_PRIVATE);
        addlocal();
    }

    public void getCreal() {
        SharedPreferences.Editor editor = userInfoC.edit();
        editor.putString(ConstantsValues.CITYNAMEOne, city);
        editor.putString(ConstantsValues.CITYNAME, city);
        editor.putString(ConstantsValues.CITYNAMECODE, stringCode(city));
        editor.putString(ConstantsValues.CITYNAMEOneCode, stringCode(city));
        editor.putString(ConstantsValues.province, "四川省");
        editor.putString(ConstantsValues.longitude, "0");
        editor.putString(ConstantsValues.ZUOBIAO, "0;0");
        editor.putString(ConstantsValues.latitude, "0");
        editor.commit();
        Logger.i("定位开始");
        if (locationService != null) {
            Logger.i("开始定位服务");
            locationService.start(); //开始定位服务
        }

    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    public BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            Logger.i("111111111111");
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                Logger.i("定位开始执行  " + location.getCity());
                SharedPreferences.Editor editor = userInfoC.edit();
                try {
                    editor.putString(ConstantsValues.CITYNAMEOne, CheckUtils.checkCity(location.getCity()));
                } catch (ApiException e) {
                    editor.putString(ConstantsValues.CITYNAMEOne, e.getMessage());
                }
                if (userInfoC.getString(ConstantsValues.CITYNAME, "").equals("") || types) {
                    try {
                        city = CheckUtils.checkCity(location.getCity());
                    } catch (ApiException e) {
                        city = e.getMessage();
                    }
                    editor.putString(ConstantsValues.CITYNAME, city);
                    editor.putString(ConstantsValues.CITYNAMECODE, stringCode(city));
                }
                editor.putString(ConstantsValues.CITYNAMEOneCode, stringCode(city));
                editor.putString(ConstantsValues.province, location.getProvince());
                editor.putString(ConstantsValues.longitude, "" + location.getLongitude());
                editor.putString(ConstantsValues.ZUOBIAO, location.getLatitude() + ";" + location.getLongitude());
                editor.putString(ConstantsValues.latitude, "" + location.getLatitude());
                editor.commit();
                locationService.stop();
                //发送Action为com.example.communication.RECEIVER的广播
            } else {
                Logger.i("定位失败  ");
            }
            sendBroadcast(intent);
        }
    };

    public void addlocal() {
        stringArrayList(Utils.getJson(this, "city.txt"));
        locationService = new LocationService(this);
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);


    }

    private String stringCode(String s) {
        for (MembersAdresssBean bean : arry_address) {
            if (CheckUtils.containsString(bean.getArea_name(), s)) {
                return bean.getArea_code();
            }
        }
        if (CheckUtils.containsString(s, "杭州")) {
            return "330100";
        }
        return "000000";
    }


    private void stringArrayList(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray jsonArray = JsonUtil.getJSONArray(jsonObject, "RECORDS");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = JsonUtil.getJSONObject(jsonArray, i);
                if (JsonUtil.getString(jsonObject, "level").equals("2")) {
                    bean = new MembersAdresssBean();
                    bean.setArea_code(JsonUtil.getString(jsonObject, "area_code"));
                    try {
                        bean.setArea_name(CheckUtils.checkCity(JsonUtil.getString(jsonObject, "area_name")));
                    } catch (ApiException e) {
                        bean.setArea_name(e.getMessage());
                    }
                    bean.setArea_name(JsonUtil.getString(jsonObject, "area_name"));
                    bean.setLevel(JsonUtil.getString(jsonObject, "level"));
                    bean.setParent_area_code(JsonUtil.getString(jsonObject, "parent_area_code"));
                    arry_address.add(bean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //实现一个接口，然后我们就在绑定服务的时候拿到这个Binder对象，然后调用接口里面的方法
    class MyBinder extends Binder implements IService {

        @Override
        public void invokeServiceMethod(boolean type) {
            types = type;
            //调用Service里面的方法
            getCreal();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
        }
    }
}
